package org.btik.light.server.dev.manage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.btik.light.meta.*;
import org.btik.light.meta.event.DevEvent;
import org.btik.light.meta.event.DevEventListener;
import org.btik.light.server.platform.common.api.service.DevMetaService;
import org.btik.light.server.platform.common.api.dao.LightDao;
import org.btik.light.server.platform.event.ConnectEvent;
import org.btik.light.server.platform.manage.DevEventDispatcher;

import java.util.Map;
import java.util.Objects;

/**
 * @author lustre
 * @since 2023/3/8 12:16
 */
public class DefaultDevEventListener implements DevEventListener {
    private final Log log = LogFactory.getLog(DevEventDispatcher.class);

    private LightDao lightDao;


    private DevMetaService devMetaService;


    private Map<String, ConnectHandler> connectHandlerMap;


    @Override
    public void onConnected(DevEvent devEvent) {
        log.info(devEvent.getDev() + " is connected!");
        if (!(devEvent instanceof ConnectEvent connectEvent)) {
            return;
        }
        DevMo devMO = connectEvent.getDevMO();
        DevMeta meta = devMetaService.getMeta(devMO.getDevType(), devMO.getVersion());
        if (Objects.nonNull(meta)) {
            meta.setProp(devMO);
        }
        devMO.setExtendedAttribute(LightDevAttrConstant.DEV_AREA, DevArea.CLOUD.name());
        ConnectHandler connectHandler = connectHandlerMap.get(devMO.getDevType());
        if (connectHandler != null) {
            connectHandler.onConnect(devMO);
        }
        LightNode thisSystemNode = lightDao.getThisSystemNode();
        lightDao.addDev(thisSystemNode, devMO);


    }

    @Override
    public void onDisConnected(DevEvent devEvent) {
        String dev = devEvent.getDev();
        DevMo mo = lightDao.getMO(dev);
        mo.setDevState(DevState.DISCONNECTED);
    }

    public void setLightDao(LightDao lightDao) {
        this.lightDao = lightDao;
    }

    public void setDevMetaService(DevMetaService devMetaService) {
        this.devMetaService = devMetaService;
    }

    public void setConnectHandlerMap(Map<String, ConnectHandler> connectHandlerMap) {
        this.connectHandlerMap = connectHandlerMap;
    }
}
